package com.cinema.api.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cinema.api.mapper.ArrangementMapper;
import com.cinema.api.mapper.FilmMapper;
import com.cinema.api.model.dto.CartDTO;
import com.cinema.api.model.entity.Arrangement;
import com.cinema.api.model.entity.Cart;
import com.cinema.api.mapper.CartMapper;
import com.cinema.api.model.entity.Film;
import com.cinema.api.service.CartService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cinema.api.utils.BaseUtil;
import com.cinema.api.utils.DataTimeUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xhh
 * @since 2021-12-31
 */
@Service
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements CartService {

    @Resource
    private CartMapper cartMapper;

    @Resource
    private FilmMapper filmMapper;

    @Resource
    private ArrangementMapper arrangementMapper;

    @Override
    public void add(Cart cart) {
        cart.setCreateTime(DataTimeUtil.getNowTimeString());
        cart.setIsDelete(0);
        // 默认购物车状态
        cart.setStatus(0);
        cartMapper.insert(cart);
    }

    /**
     * 根据用户id查询购物车
     * 返回对象电影、排片、订单List
     */
    @Override
    public List<CartDTO> findAllByUid(String uid) {
        List<CartDTO> result = new ArrayList<>();
        QueryWrapper<Cart> wrapper = new QueryWrapper<>();
        wrapper.in("uid", uid)
                .eq("is_delete", 0);
        List<Cart> carts = cartMapper.selectList(wrapper);
        for (Cart cart : carts) {
            Arrangement arrangement = arrangementMapper.selectById(cart.getAid());
            if (BaseUtil.isNotEmpty(arrangement)) {
                Film film = filmMapper.selectById(arrangement.getFid());
                CartDTO cartDTO = new CartDTO(film, arrangement, cart);
                result.add(cartDTO);
            }
        }
        return result;
    }

    /**
     * 根据Id删除购物车
     */
    @Override
    public void deleteById(String id) {
        cartMapper.deleteById(id);
    }
}
